<script lang="ts">
	import { USER_ROLE } from '$lib/api/proto/user_api';
	import SimpleEditor from '$lib/components/editor/SimpleEditor.svelte';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import EditorJS from '@editorjs/editorjs';

	interface Props {
		onClose: () => void;
	}
	let props: Props = $props();

	let userRole = $state(userStore.userInfo?.basicInfo?.userRole ?? USER_ROLE.USER_ROLE_STUDENT);
	let introEditor: EditorJS | null = $state(null);

	async function updateUserInfo() {
		if (
			userStore.userSession == null ||
			userStore.userInfo?.basicInfo == undefined ||
			introEditor == null
		) {
			return;
		}

		const introData = await introEditor.save();

		await callApi(
			appStore.userApiClient.updateBasic({
				sessionId: userStore.userSession,
				basicInfo: {
					...userStore.userInfo.basicInfo,
					userRole: userRole,
					userIntro: JSON.stringify(introData)
				}
			}).response
		);
		userStore.userInfo = {
			...userStore.userInfo,
			basicInfo: {
				...userStore.userInfo.basicInfo,
				userRole: userRole,
				userIntro: JSON.stringify(introData)
			}
		};
		props.onClose();
	}
</script>

<dialog class="modal modal-open">
	<div class="modal-box w-[800px] max-w-none">
		<button
			class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2"
			onclick={() => props.onClose()}>✕</button
		>
		<h3 class="text-lg font-bold">修改用户信息</h3>
		<div class="max-h-[60vh] overflow-y-auto pr-[10px] flex-col space-y-4 pt-[20px]">
			<label class="label w-full">
				<span class="label w-[100px] text-right inline-block pr-[10px]">角色:</span>
				<select class="select w-full" bind:value={userRole}>
					<option value={USER_ROLE.USER_ROLE_COACH}>教练</option>
					<option value={USER_ROLE.USER_ROLE_STUDENT}>学生</option>
				</select>
			</label>
			<h4 class="text-base font-bold">用户简介</h4>
			<SimpleEditor
				sizeClass="min-h-[300px] border-2 border-base-200 max-h-[300px]"
				placeholder="请输入用户简介"
				onInit={(tmpEditor) => (introEditor = tmpEditor)}
			/>
		</div>
		<div class="modal-action">
			<button class="btn" onclick={() => props.onClose()}>取消</button>
			<button class="btn btn-primary" onclick={() => updateUserInfo()}>修改</button>
		</div>
	</div>
	<div class="modal-backdrop">
		<button onclick={() => props.onClose()}>close</button>
	</div>
</dialog>
